package com.example.gamestore.control;

import com.example.gamestore.Bean.PaymentBo;
import com.example.gamestore.Bean.User;
import com.example.gamestore.mapper.UserMapper;
import com.example.gamestore.service.imp.PayService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping(value = "/pay")
public class PayControl {
    @Autowired
    private PayService payService;
    @Autowired
    private UserMapper userMapper;
    /**
     *  下单支付
     * */
    @GetMapping(value = "/confirm" , produces = {"text/html;charset=UTF-8"})
    public Object pay (@RequestParam(required = false,value = "money") Integer money,
                       @RequestParam(required = false,value = "money1") Integer money1,
                       HttpSession session) throws Exception {
        //这个接口其实应该是post方式的，但是我这里图方便，直接以get方式访问，
        //且返回格式是text/html，这样前端页面就能直接显示支付宝返回的html片段
        //真实场景下由post方式请求，返回code、msg、data那种格式的标准结构，让前端拿到data里的
        //html片段之后自行加载
        PaymentBo bo=new PaymentBo();
        if(money!=null&&money1==null){
            bo.setMoney(money);
        }
        if(money1!=null&&money==null){
            bo.setMoney(money1);
        }
        bo.setSubject("劲松币");

        User user=(User) session.getAttribute("user");
        bo.setId(user.getId());
        System.out.println(666);
        return payService.pay(bo);
    }

    /**
     *  支付成功的回调
     * */
    @PostMapping(value = "/fallback")
    public Object fallback (HttpServletRequest request) {
        Map map = request.getParameterMap();
        success(map);
        return null;
    }
    /**
     * 支付成功后改变用户的余额
     */
    public void success(Map map){
        String[] id =(String[]) map.get("out_trade_no");
        String[] account=(String[]) map.get("total_amount");
        String money=account[0];
        String substring = money.substring(0, money.length() - 3);
        String orderid=id[0];
        String userid = orderid.substring(orderid.length() - 1);
        int money1 = Integer.parseInt(substring);
        int id1 = Integer.parseInt(userid);
        User user1 = userMapper.selectById(id1);
        Integer account1 = user1.getAccount();
        user1.setAccount(account1+money1);
        userMapper.updateById(user1);
        System.out.println(user1);
    }
}
